package me.flyray.auth.feignserver;

import java.util.HashMap;
import java.util.Map;

import me.flyray.auth.common.config.UserAuthConfig;
import me.flyray.auth.common.vo.JwtAuthenticationRequest;
import me.flyray.auth.common.vo.JwtAuthenticationResponse;
import me.flyray.auth.service.AuthService;
import me.flyray.common.exception.BusinessException;
import me.flyray.common.msg.BaseApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import me.flyray.common.msg.ResponseCode;

import javax.servlet.http.HttpServletRequest;

/**
 * @author bolei
 * @create 2018-4-2 20:30
 * 业务系统登陆授权接口，通过feign调用
 */
@Controller
@RequestMapping("feign/auth")
public class FeignUserAuth {

	@Autowired
	protected HttpServletRequest request;
	@Autowired
	private UserAuthConfig userAuthConfig;
	@Value("${jwt.token-header}")
	private String tokenHeader;
	@Autowired
	private AuthService authService;
	
	@RequestMapping(value = "/getAdminUserToken",method = RequestMethod.POST)
    @ResponseBody
    public BaseApiResponse<JwtAuthenticationResponse> getAdminUserToken(@RequestBody JwtAuthenticationRequest request) {
		JwtAuthenticationResponse response = null;
		try {
			response = authService.getAdminUserToken(request);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException(ResponseCode.CUST_NOTEXIST);
		}
		return BaseApiResponse.newSuccess(response);
	}

	@RequestMapping(value = "/getBizUserToken",method = RequestMethod.POST)
	@ResponseBody
	public BaseApiResponse<JwtAuthenticationResponse> getBizUserToken(@RequestBody JwtAuthenticationRequest request) {
		JwtAuthenticationResponse response = null;
		try {
			response = authService.getBizUserToken(request);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException(ResponseCode.CUST_NOTEXIST);
		}
		return BaseApiResponse.newSuccess(response);
	}

	@RequestMapping(value = "refresh", method = RequestMethod.GET)
	public BaseApiResponse<String> refreshAndGetAuthenticationToken(
			HttpServletRequest request) throws Exception {
		String token = request.getHeader(tokenHeader);
		String refreshedToken = authService.refresh(token);
		return BaseApiResponse.newSuccess(refreshedToken);
	}

	@RequestMapping(value = "verify", method = RequestMethod.GET)
	public BaseApiResponse<?> verify() throws Exception {
		authService.validate(request.getHeader(userAuthConfig.getTokenHeader()));
		return BaseApiResponse.newSuccess();
	}

}
